<script setup>
import { CateDelService, CateGetListService } from '@/api/user.js'
import {ref} from 'vue'
import {onMounted} from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import ChannelEdit from '@/views/article/components/ChannelEdit.vue'

const cate = ref([])
const getCate = async () => {
  loading.value = true
  const info = await CateGetListService()
  cate.value = info.data.data
  console.log(cate.value)
  loading.value = false
}

onMounted(async () => {
  getCate()
})

const openDialog = (row) => {
  // 打开弹窗
  dialog.value.open(row)
}

const loading = ref(true)

const deleteCate = async (row) => {  // 改为 async 函数
  try {
    await ElMessageBox.confirm(
      `确认删除文章分类"${row.cate_name}"?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 确认删除后执行
    await CateDelService(row.id)  // 等待删除操作完成
    ElMessage.success('删除成功')  // 提示成功
    await getCate()               // 等待刷新数据
  } catch (error) {
    if (error !== 'cancel') {     // 用户点击了取消（非删除失败）
      ElMessage.error('删除失败: ' + error.message) // 可提示具体错误
    } else {
      ElMessage.info('取消删除')  // 用户取消操作
    }
  }
}

const dialog = ref()
const OnSuccess = () => {
  getCate()
}
</script>

<template>
  <page-container title="文章分类">
    <template #extra>
      <el-button type="primary" @click="openDialog">添加分类</el-button>
    </template>
      <el-table v-loading="loading" :data="cate" style="width: 100% ">
        <el-table-column label="序号" width="120" >
          <template #default=" {$index} ">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类名称"/>
        <el-table-column prop="cate_alias" label="分类别名" />
        <el-table-column label="操作" width="150">
          <template #default="{row, $index}">
            <el-button type="primary" :icon="Edit" circle plain
                       @click="openDialog(row)"/>
            <el-button
              type="danger" :icon="Delete" circle plain
              @click="deleteCate(row,$index)"/>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="description" />
        </template>
      </el-table>
  </page-container>
  <channel-edit ref="dialog" @success="OnSuccess"></channel-edit>
</template>
